//
//  ClubDetailController.swift
//  BodyBuilding
//
//  Created by franze on 2017/10/3.
//  Copyright © 2017年 franze. All rights reserved.
//

import UIKit

class ClubDetailController: UIViewController,UITableViewDelegate,UITableViewDataSource {
    var infoDict:NSDictionary!
    var courseArray:NSArray?
    var btnView:YButtonView!
    var mainScrollView:UIScrollView!
    var tableView:UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        viewConfig()
        getCourseList()
    }
    
    func viewConfig(){
        view.backgroundColor = UIColor(red: 245/255, green: 245/255, blue: 245/255, alpha: 1)
        
        let navBar = CustomNavBar(frame: CGRect(origin: .zero, size: CGSize(width: WIDTH, height: 64)))
        navBar.initialize(text: nil)
        view.addSubview(navBar)
        
        let scrollView = YScrollView(frame: CGRect(origin: CGPoint(x:0, y:64), size: CGSize(width: WIDTH, height: HEIGHT/4)))
        view.addSubview(scrollView)
        Networking.shared.fetchImage { (array) in
            var images:[String] = []
            var ids:[String] = []
            for obj in array{
                let dict = obj as! NSDictionary
                let str = dict.value(forKey: "thumb") as! String
                let imgStr = BB_IMAGEURLPRE + str
                images.append(imgStr)
                
                let id = dict.value(forKey: "id") as! String
                ids.append(id)
            }
            scrollView.ids = ids
            scrollView.initialize(images: images)
            scrollView.pageControlInit(view: self.view)
        }
        
        mainScrollView = UIScrollView(frame: CGRect(x: 0, y: 64+scrollView.bounds.height+56, width: WIDTH, height: HEIGHT-64))
        mainScrollView.contentSize = CGSize(width: WIDTH*2, height: 0)
        mainScrollView.contentInsetAdjustmentBehavior = .never
        mainScrollView.backgroundColor = view.backgroundColor
        mainScrollView.isScrollEnabled = false
        view.addSubview(mainScrollView)
        
        btnView = YButtonView(frame: CGRect(x: 0, y: 70+scrollView.bounds.height, width: WIDTH, height: 54))
        btnView.initialize(titles: ["简介","课程"])
        btnView.backgroundColor = UIColor.white
        view.addSubview(btnView)
        
        let textView = UITextView(frame: CGRect(x: 15, y: 10, width: WIDTH-30, height: 140))
        textView.text = infoDict.value(forKey: "introduction") as! String
        textView.isEditable = false
        textView.font = UIFont.systemFont(ofSize: 16)
        textView.layer.borderWidth = 1
        textView.layer.borderColor = UIColor.lightGray.cgColor
        mainScrollView.addSubview(textView)
        
        let telLabel = UILabel(frame: CGRect(x: 15, y: textView.frame.origin.y+160, width: WIDTH-30, height: 20))
        telLabel.text = "联系电话: \(infoDict.value(forKey: "club_tel") as! String)"
        telLabel.font = UIFont.systemFont(ofSize: 20)
        mainScrollView.addSubview(telLabel)
        
        let addrLabel = UILabel(frame: CGRect(x: 15, y: telLabel.frame.origin.y+40, width: WIDTH-30, height: 20))
        let addr = (infoDict.value(forKey: "province_name") as! String)+(infoDict.value(forKey: "city_name") as! String)+(infoDict.value(forKey: "district_name") as! String)
        addrLabel.text = "具体地址: \(addr)"
        addrLabel.font = UIFont.systemFont(ofSize: 20)
        mainScrollView.addSubview(addrLabel)
        
        let joinBtn = CustomButton(frame: CGRect(x: 0, y: addrLabel.frame.origin.y+60, width: 150, height: 44))
        joinBtn.backgroundColor = UIColor.red
        joinBtn.center.x = WIDTH/2
        joinBtn.setTitle("关注", for: .normal)
        joinBtn.layer.cornerRadius = 8
        joinBtn.adjustsImageWhenDisabled = false
        joinBtn.isEnabled = false
        joinBtn.animation()
        mainScrollView.addSubview(joinBtn)
        
        tableView = UITableView(frame: CGRect(x: WIDTH, y: 0, width: WIDTH, height: mainScrollView.bounds.height))
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        tableView.backgroundColor = view.backgroundColor
        tableView.delegate = self
        tableView.dataSource = self
        mainScrollView.addSubview(tableView)
        
        isExits(sender: joinBtn)
        
        joinBtn.addTarget(self, action: #selector(joinClub), for: .touchUpInside)
        navBar.backBtn.addTarget(self, action: #selector(back), for: .touchUpInside)
        btnView.firstBtn.addTarget(self, action: #selector(onClick), for: .touchUpInside)
        btnView.secondBtn.addTarget(self, action: #selector(onClick), for: .touchUpInside)
        
        let parameter:NSMutableDictionary = [
            "SessionID"     :   LoginModel.sessionID
        ]
        let controller = CourseDetailController()
        scrollView.imageGesture(firstAction: { (id) in
            scrollView.isUserInteractionEnabled = false
            parameter.setValue(id, forKey: "id")
            Networking.shared.getCourseDetail(parameter: parameter, block: { (dict) in
                controller.infoDict = dict
                self.hidesBottomBarWhenPushed = true
                _ = self.navigationController?.pushViewController(controller, animated: true)
                scrollView.isUserInteractionEnabled = true
            })
        }, secondAction: { (id) in
            scrollView.isUserInteractionEnabled = false
            parameter.setValue(id, forKey: "id")
            Networking.shared.getCourseDetail(parameter: parameter, block: { (dict) in
                controller.infoDict = dict
                self.hidesBottomBarWhenPushed = true
                _ = self.navigationController?.pushViewController(controller, animated: true)
                scrollView.isUserInteractionEnabled = true
            })
        }) { (id) in
            scrollView.isUserInteractionEnabled = false
            parameter.setValue(id, forKey: "id")
            Networking.shared.getCourseDetail(parameter: parameter, block: { (dict) in
                controller.infoDict = dict
                self.hidesBottomBarWhenPushed = true
                _ = self.navigationController?.pushViewController(controller, animated: true)
                scrollView.isUserInteractionEnabled = true
            })
        }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return courseArray?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell")
        
        cell.backgroundColor = view.backgroundColor
        let dict = courseArray![indexPath.row] as! NSDictionary
        cell.textLabel?.text = dict.value(forKey: "course_name") as? String
        cell.detailTextLabel?.text = "截止日期: " + (dict.value(forKey: "end_date") as? String)!
        let label = UILabel(frame: CGRect(x: WIDTH-15-50, y: 0, width: 50, height: 50))
        label.text = (dict.value(forKey: "course_price") as? String)! + "元"
        cell.addSubview(label)
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 50
    }
    
    func getCourseList(){
        let parameter:NSDictionary = [
            "SessionID"  : LoginModel.sessionID,
            "id"         : infoDict.value(forKey: "id") as! String,
            "related"    : "1",
            "mod"        : "club"
        ]
        Networking.shared.getCourse(parameter: parameter) { (dict) in
            self.courseArray = dict.value(forKey: "Clubcourse") as? NSArray
            self.tableView.reloadData()
            print(self.courseArray!)
        }
    }
    
    func isExits(sender:CustomButton){
        let parameters:NSDictionary = [
            "SessionID"     :   LoginModel.sessionID,
            "fan_id"        :   infoDict.value(forKey: "id") as! String,
            "userid"        :   LoginModel.userID,
            "fans_type"     :   "1",
        ]
        Networking.shared.isExits(parameter: parameters) {(success) in
            DispatchQueue.main.async {
            if success{
                sender.setTitle("取消关注", for: .normal)
            }
            sender.stopAnimation()
            sender.isEnabled = true
            }
        }
    }
    
    @objc func joinClub(sender:UIButton){
        let parameter:NSDictionary = [
            "SessionID" :   LoginModel.sessionID,
            "fan_id"    :   infoDict.value(forKey: "id") as! String,
            "fans_type" :   "1",
            "userid"    :   LoginModel.userID
        ]
        if sender.isEnabled{
            let popup = Popup()
            if sender.titleLabel?.text == "关注"{
                Networking.shared.focus_Join(parameter: parameter) {
                    DispatchQueue.main.async {
                        popup.appear(title: "关注成功", action: nil)
                        sender.setTitle("取消关注", for: .normal)
                    }
                }
            }else{
                Networking.shared.delete(parameter: parameter, block: {
                    DispatchQueue.main.async {
                        popup.appear(title: "取消关注成功", action: nil)
                        sender.setTitle("关注", for: .normal)
                    }
                })
            }
        }
    }
    
    @objc func onClick(sender:UIButton){
        let circle = btnView.circle!
        circle.anim.location = sender.center
        switch sender.tag {
        case 1:
            if circle.c2 != circle.c1{
                circle.anim.direction = "left"
                circle.link.isPaused = false
                mainScrollView.setContentOffset(CGPoint(x:0,y:0), animated: true)
            }
        case 2:
            if circle.c2 == circle.c1{
                circle.anim.direction = "right"
                circle.link.isPaused = false
                mainScrollView.setContentOffset(CGPoint(x:WIDTH,y:0), animated: true)
            }
        default:
            break
        }
    }
    
    @objc func back(){
        _ = navigationController?.popViewController(animated: true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}
